﻿using System.Collections;
using System.Collections.Generic;
using Pumpkin.Utils;
using Object = UnityEngine.Object;
using LitJson;

namespace Pumpkin.FrameBase.Template
{
    public class TemplateLoader : IModuleComponent
    {
        public class ConfigContentItem
        {
            public string FileName;
            public string ClsName;
            public bool IsArray;
        }

        private List<ConfigContentItem> configContents_ = new List<ConfigContentItem>();
        private CrossDomainInfo crossConfigLoader;
        private IFrameModule module_;
        public void Init()
        {
            crossConfigLoader = CrossDomainInfoFactory.Instance.Create(BaseCrossType.ConfigLoader);
            CoroutineManager.DoCoroutine(LoadConfig());
        }

        public void SetModule(IFrameModule module)
        {
            module_ = module;
        }

        private IEnumerator LoadConfig()
        {
            var configRootPath = FileHelper.CombinePath(HotFixConfigs.ConfigPath, HotFixConfigs.ConfigRootFile);
            var configContentData = ResHelper.LoadAsset<Object>(configRootPath, true).ToString();

            configContents_ = JsonMapper.ToObject<List<ConfigContentItem>>(configContentData);
            var args = new object[3];
            foreach (var item in configContents_)
            {
                var path = FileHelper.CombinePath(HotFixConfigs.ConfigPath, item.FileName);
                var configData = ResHelper.LoadAsset<Object>(path).ToString();
                args[0] = item.ClsName;
                args[1] = configData;
                args[2] = item.IsArray;
                crossConfigLoader.StaticInvoke("Load", args);
                yield return null;
            }

            if (GlobalConfigs.Instance.HotFixEnabled())
            {
                string configBundleName = FileHelper.ABPathToCombName(HotFixConfigs.ConfigPath);
                ResHelper.UnLoadBundle(configBundleName);
            }
            Log.LogDebug("Init Game Finish", LogColor.Yellow);
            module_.OnLoaded();
        }
    }
}
